package com.y2w.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.y2w.gulimall.member.dao.MemberLevelDao;
import com.y2w.gulimall.member.entity.MemberLevelEntity;
import com.y2w.gulimall.member.exception.EmailExistException;
import com.y2w.gulimall.member.exception.PhoneExistException;
import com.y2w.gulimall.member.exception.UserNameExistException;
import com.y2w.gulimall.member.vo.MemberLoginVo;
import com.y2w.gulimall.member.vo.MemberRegistVo;
import com.y2w.gulimall.member.vo.SocialUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.y2w.common.utils.PageUtils;
import com.y2w.common.utils.Query;

import com.y2w.gulimall.member.dao.MemberDao;
import com.y2w.gulimall.member.entity.MemberEntity;
import com.y2w.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setMobile(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());

        memberEntity.setNickname(vo.getUserName());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode("123456");
        memberEntity.setPassword(encode);

        memberDao.insert(memberEntity);
    }

    @Override
    public void checkEmailUnique(String email) throws EmailExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("email", email));
        if (count > 0) {
            throw new EmailExistException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameExistException();
        }

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //    去数据库查
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity == null) {
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser s, String user) {
        String substring = user.substring(1, user.length() - 1);
        String[] fields = substring.split(",");
        Map <String,String>userMap = new HashMap<>();
        if (fields != null && fields.length > 0) {
            for (String field : fields) {
                String[] split = field.split("=");
                userMap.put(split[0].trim(), split[1].trim());
            }
        }
        if (userMap != null && userMap.size() > 0) {
            String uid=userMap.get("id");
            //    判断是否已注册
            MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
            if (memberEntity != null) {
                MemberEntity entity = new MemberEntity();
                entity.setId(memberEntity.getId());
                entity.setAccessToken(s.getAccess_token());
                entity.setExpiresIn(Long.valueOf(s.getExpires_in()));
                updateById(entity);

                memberEntity.setExpiresIn(Long.valueOf(s.getExpires_in()));
                memberEntity.setAccessToken(s.getAccess_token());
                return memberEntity;
            } else {
                //    注册
                MemberEntity entity = new MemberEntity();
                String name = userMap.get("name");
                if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(uid)&&!name.equals("null")&&!uid.equals("null")) {
                    entity.setNickname(name);
                    entity.setSocialUid(uid);
                    entity.setAccessToken(s.getAccess_token());
                    entity.setExpiresIn(Long.valueOf(s.getExpires_in()));
                    baseMapper.insert(entity);
                    return entity;
                }
            }
        }
        return null;
    }


}
